import {createSlice} from "@reduxjs/toolkit";
import {getToken, setToken as _setToken, removeToken} from "@/utils";
import {findUserAPI, loginUserAPI} from "@/apis";

const useStore = createSlice({
    name: "users",
    // 初始化状态
    initialState: {
        token: getToken() || "",
        userInfo: {}
    },
    // 同步修改状态
    reducers: {
        SetToken(state, action) {
            state.token = action.payload
            // token 持久化 存储到localstorage里面
            _setToken(action.payload)
        },
        SetUserInfo(state, action) {
            state.userInfo = action.payload
        },
        clearToken(state) {
            state.token = ""
            state.userInfo = {}
            removeToken()
        }
    }
})


// 解构赋值
const {SetToken, SetUserInfo, clearToken} = useStore.actions


// 异步修改状态
const AsyncSetToken = (LoginForm) => {
    return async (dispatch) => {
        // 发送异步请求
        const res = await loginUserAPI(LoginForm)
        // 设置token
        dispatch(SetToken(res.data.token))
    }
}

const AsyncGetUserInfo = () => {
    return async (dispatch) => {
        // 发送异步请求
        const res = await findUserAPI()
        // 拿到身份信息
        dispatch(SetUserInfo(res.data))
    }
}

export {AsyncSetToken, AsyncGetUserInfo, SetToken, clearToken}
const UserReducer = useStore.reducer
export default UserReducer